/***************************************************************************************
 The copyright in this software is being made available under the BSD License, included
 below. This software may be subject to other third party rights,including patent rights,
 and no such rights are granted under this license.

 Regents of the Tsinghua University, Peking University, Zhejiang University, HKUST
 Tsinghua University, Peking University, Zhejiang University, HKUST 2011

 Copyright (c) 2011, Regents of the Tsinghua University, Peking University, Zhejiang
 University, HKUST. All Rights Reserved.

 Redistribution and use in source and binary forms, with or without modification, are
 permitted provided that the following conditions are met:
   * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright notice,
     this list of conditions and the following disclaimer in the documentation
     and/or other materials provided with the distribution.
   * Neither the names of the copyright holders nor the names of its
     contributors may be used to endorse or promote products derived from this
     software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 OF SUCH DAMAGE.
***************************************************************************************/


#include <stdlib.h>

#include "contributors.h"
#include "bbv.h"

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
int check_bbs_size( int profile, int level, int *bbs_size )
{
    switch ( level )
    {
        case 0x08:
            if ( *bbs_size > 61440 )
            {
                printf( "The size of BBS is larger than upper bound in the level 0x08.\n" );
                *bbs_size = 61440;
                return FALSE;
            }
            break;
        case 0x10:
            if ( *bbs_size > 122880 )
            {
                printf( "The size of BBS is larger than upper bound in the level 0x10.\n" );
                *bbs_size = 122880;
                return FALSE;
            }
            break;
        case 0x11:
            if ( *bbs_size > 311296 )
            {
                printf( "The size of BBS is larger than upper bound in the level 0x11.\n" );
                *bbs_size = 311296;
                return FALSE;
            }
            break;
        case 0x20:
            if ( *bbs_size > 1228800 )
            {
                printf( "The size of BBS is larger than upper bound in the level 0x20.\n" );
                *bbs_size = 1228800;
                return FALSE;
            }
            break;
        case 0x22:
            if ( *bbs_size > 1851392 )
            {
                printf( "The size of BBS is larger than upper bound in the level 0x22.\n" );
                *bbs_size = 1851392;
                return FALSE;
            }
            break;
        case 0x40:
            if ( *bbs_size > 2457600 )
            {
                printf( "The size of BBS is larger than upper bound in the level 0x40.\n" );
                *bbs_size = 2457600;
                return FALSE;
            }
            break;
        case 0x41:
            if ( *bbs_size > 6144000 )
            {
                printf( "The size of BBS is larger than upper bound in the level 0x41.\n" );
                *bbs_size = 6144000;
                return FALSE;
            }
            break;
        case 0x42:
            if ( *bbs_size > 3686400 )
            {
                printf( "The size of BBS is larger than upper bound in the level 0x42.\n" );
                *bbs_size = 3686400;
                return FALSE;
            }
            break;
        case 0x44:
            break; //xy_110913

        default:
            printf( "The level %x is invalid.\n", level );
            return FALSE;
            break;
    }
    return TRUE;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
bbv_buffer_t *init_bbv_memory( input_t * pInput )
{
    bbv_buffer_t *p_bbv;
    static float frame_rate_table[] = { 23.97f, 24.00f, 25.00f, 29.97f, 30.00f, 50.00f, 59.97f, 60.00f };

    if ( NULL == ( p_bbv = ( bbv_buffer_t * ) calloc( 1, sizeof( bbv_buffer_t ) ) ) )
    {
        printf( "memory for bbv buffer have error.\n" );
        return NULL;
    }

    if ( NULL == ( p_bbv->frame_bits = ( int * )calloc( 1, 1000000 * sizeof( int ) ) ) )
    {
        printf( "memory for frame bits of bbv buffer have error.\n" );
        return NULL;
    }

    p_bbv->frame_rate       = frame_rate_table[pInput->frame_rate_code - 1];
    p_bbv->frm_no          = 0;
    p_bbv->bbv_mode        = pInput->bbv_mode;
    p_bbv->low_delay       = ( float )pInput->low_delay;
    p_bbv->frm_out_interval = ( float )( 1.0 / p_bbv->frame_rate );
    p_bbv->bitrate         = pInput->bit_rate;
    p_bbv->bbs_size        = pInput->bbv_buf_size << 14;
    p_bbv->bbv_delay       = ( float )( 0.5 * p_bbv->bbs_size / p_bbv->bitrate );
    p_bbv->check_continue  = 1;
    p_bbv->curr_frm_max_bit = p_bbv->bbs_size;
    p_bbv->curr_frm_min_bit = 0;

    return p_bbv;
}


/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
bbv_buffer_t *free_bbv_memory( bbv_buffer_t * p_bbv )
{
    free( p_bbv->frame_bits );
    p_bbv->frame_bits = NULL;
    free( p_bbv );
    p_bbv = NULL;

    return p_bbv;
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void update_bbv( bbv_buffer_t * p_bbv, int code_bits )
{
    p_bbv->frame_bits[p_bbv->frm_no++] = code_bits;
    if ( ( code_bits < p_bbv->curr_frm_min_bit ) && !p_bbv->low_delay && p_bbv->check_continue )
    {
        printf( "Overflow will occur at the next time intervals between successive examination!\nThe removing data at the current decoding time (Image NO.%d) is %d.\n The removing data should be %d in order to avoid overflow.\n", p_bbv->frm_no + ( B_IMG == img->type ? ( -2 ) : ( 1 ) ),
                code_bits, p_bbv->curr_frm_min_bit );

        printf( "Image No.%d code bits is %d, less than lower bound %d\n\n", p_bbv->frm_no + ( B_IMG == img->type ? ( -2 ) : ( 1 ) ), code_bits, p_bbv->curr_frm_min_bit );
        p_bbv->check_continue = 0;
    }
    if ( code_bits > p_bbv->curr_frm_max_bit && p_bbv->check_continue )
    {
        printf( "Underflow occurs at the current decoding time (Image NO.%d)!\nThe data in BBV buffer is %d, whereas the removing data is %d.\n", p_bbv->frm_no + ( B_IMG == img->type ? ( -2 ) : ( 1 ) ), p_bbv->curr_frm_max_bit, code_bits );
        p_bbv->check_continue = 0;
    }

    if ( p_bbv->bbv_mode )
    {
        p_bbv->curr_frm_max_bit = RFM_MIN( p_bbv->bbs_size, ( int )( p_bbv->curr_frm_max_bit - code_bits + p_bbv->bitrate * p_bbv->frm_out_interval + 0.5 ) );
        p_bbv->curr_frm_min_bit = 0;
    }
    else
    {
        p_bbv->bbv_delay += p_bbv->frm_out_interval - ( ( float )code_bits ) / ( ( float )p_bbv->bitrate );
        p_bbv->curr_frm_max_bit = ( int )( p_bbv->bbv_delay * p_bbv->bitrate + 0.5 );
        p_bbv->curr_frm_min_bit = RFM_MAX( 0, ( int )( ( p_bbv->bbv_delay + p_bbv->frm_out_interval ) * p_bbv->bitrate - p_bbv->bbs_size + 0.5 ) );
    }
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void stat_bbv_buffer( bbv_buffer_t * p_bbv )
{
    int minBBSsize, minFsize;

    calc_min_bbs_size( p_bbv->frame_bits, p_bbv->bitrate, p_bbv->frame_rate, p_bbv->frm_no, &minBBSsize, &minFsize );
    printf( "min bbv_buf_size in bitstream is %d\n", ( ( minBBSsize >> 14 ) + ( minBBSsize & 0x3FFF ? 1 : 0 ) ) );
    if ( !p_bbv->bbv_mode )
    {
        printf( "min initial bbv_delay(0) time is %.4f(s)\n\n", ( float )minFsize / p_bbv->bitrate );
    }
    else
    {
        printf( "\n\n" );
    }
}

/*
*************************************************************************
* Function:
* Input:
* Output:
* Return:
* Attention:
*************************************************************************
*/
void calc_min_bbs_size( int *frame_bits, int BitRate, float FrameRate, int FrameNum, int *Bmin_out, int *Fmin_out )
{
    float B;
    float *Buff1, *Buff2;
    float minbuff;
    float Bmin, Fmin;
    int i;

    Buff1 = ( float * )calloc( FrameNum + 1, sizeof( float ) );
    Buff2 = ( float * )calloc( FrameNum, sizeof( float ) );
    B = ( float )( BitRate * 20 );

    minbuff = Buff1[FrameNum] = B;
    for ( i = FrameNum - 1; i >= 0; i-- )
    {
        Buff2[i] = Buff1[i + 1] - frame_bits[i];
        if ( Buff2[i] < minbuff )
            minbuff = Buff2[i];
        Buff1[i] = Buff2[i] + BitRate / FrameRate;
        if ( Buff1[i] > B )
            Buff1[i] = B;
    }
    Bmin = B - minbuff;
    *Bmin_out = ( int )Bmin;

    B = Bmin;
    Fmin = 0;
    Buff1[0] = Fmin;
    for ( i = 0; i < FrameNum; i++ )
    {
        Buff2[i] = Buff1[i] - frame_bits[i];
        if ( Buff2[i] < 0 )
        {
            Fmin += ( 0 - Buff2[i] );
            Buff2[i] = 0;
        }
        Buff1[i + 1] = Buff2[i] + BitRate / FrameRate;
        if ( Buff1[i + 1] > B )
            Buff1[i + 1] = B;
    }
    *Fmin_out = ( int )Fmin;

    free( Buff1 );
    free( Buff2 );
}
